package com.chance.cc.crawler.development.scripts.pdd.phone.findlist;

import com.chance.cc.crawler.sheduler.job.context.ScheduleHandlerContext;
import com.chance.cc.crawler.sheduler.job.handler.SchedulerHandler;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.vidstige.jadb.JadbDevice;

import java.io.InputStream;
import java.util.Map;
import java.util.Random;

import static com.chance.cc.crawler.sheduler.job.handler.phone.AdbShellUtils.*;

/**
 * @author lt
 * @version 1.0
 * @date 2021-05-26 10:34:12
 * @email okprog@sina.com
 */
public class PDDChildMilkListCrawlerScript extends SchedulerHandler {

    private static Logger logger = LoggerFactory.getLogger(PDDChildMilkListCrawlerScript.class);

    public static final String domain = "pdd";
    public static final String PDD_FIND_TYPE = "pdd_find_type";
    public static final String SCRIPT_TYPE = "children_milk";

    public static final String log_prefix = "device {} pdd crawler children milk ";

    @Override
    public boolean isHandle(ScheduleHandlerContext scheduleHandlerContext) {
        Map<String, String> scheduleDataMap = scheduleHandlerContext.getScheduleDataMap();
        if (StringUtils.isBlank(scheduleDataMap.get(PDD_FIND_TYPE))) {
            logger.error("pdd list find crawler need [{}]", PDD_FIND_TYPE);
            return false;
        }
        return scheduleDataMap.get(PDD_FIND_TYPE).equalsIgnoreCase(SCRIPT_TYPE);
    }

    @Override
    public void handle(ScheduleHandlerContext scheduleHandlerContext) {
        Map<String, String> scheduleDataMap = scheduleHandlerContext.getScheduleDataMap();
        JadbDevice jadbDevice = scheduleHandlerContext.getJadbDevice();

        int swipeNumbers = Integer.parseInt(scheduleDataMap.getOrDefault("phone_swipe_numbers", "3"));
        int index = 0;
        Random rand = new Random();
        while (true) {

            if (!checkAvailable(jadbDevice)) {
                continue;
            }
            try {
                //往下翻页
                int step = (int) ((rand.nextFloat() + 1) * 1000L);
                executeShell(jadbDevice, "input swipe 540 1900 540 0 " + step);

                index++;
                if (index >= swipeNumbers) {
                    logger.info(log_prefix + "开始模拟操作访问详情页",jadbDevice.getSerial());
//                String[] coordinate = getCoordinate(dumpUI(jadbDevice), "resource-id", "com.xunmeng.pinduoduo:id/tv_title");
                    Elements nodes = getNodes(dumpUI(jadbDevice), "resource-id", "com.xunmeng.pinduoduo:id/tv_title", false);
                    Element element = nodes.get(nodes.size() - 1);
                    String bounds = element.attr("bounds");
                    if (StringUtils.isNotBlank(bounds)) {
                        String[] boundsArray = bounds.split("]");
                        int xBounds = 0;
                        int yBounds = 0;
                        for (String ba : boundsArray) {
                            String[] coordinate = ba.split(",");
                            xBounds += Integer.parseInt(coordinate[0].split("\\[")[1]);
                            yBounds += Integer.parseInt(coordinate[1]);
                        }
                        executeShell(4000, jadbDevice, "input tap " + xBounds / 2 + " " + yBounds / 2);
                    }

                    for (int i = 0; i < 2; i++) {
                        step = (int) ((rand.nextFloat() + 1) * 1000L);
                        executeShell(jadbDevice, "input swipe 540 1700 540 0 " + step);
                    }
                    executeShell(jadbDevice, "input keyevent 4");
                    index = 0;
                    swipeNumbers = rand.nextInt(2) + 3;
                    logger.info(log_prefix + "返回列表页继续翻页",jadbDevice.getSerial());
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }

            index++;

        }
    }


    private static boolean checkAvailable(JadbDevice device) {

        boolean isAvailable = isAvailable(device);

        if (!isAvailable) { //不可用
            try {
                Thread.sleep(60000L);
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return isAvailable;
    }

    private static boolean isAvailable(JadbDevice device) {
        return isAvailable(device, null);
    }

    private static boolean isAvailable(JadbDevice device, InputStream inputStream) {
        String[] coordinate;
        try {
            if (inputStream == null) {
                inputStream = dumpUI(device);
            }
            coordinate = getCoordinate(inputStream, "text", "拼多多安全验证");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }

        if (coordinate != null) {
            logger.error("pdd find list device {} Jump out captcha!", device.getSerial());
            return false;
        }
        return true;
    }

    @Override
    public String domain() {
        return domain;
    }
}
